//
//  UserAccount.swift
//  MyWeibo
//
//  Created by tanchao on 15/8/1.
//  Copyright © 2015年 chaoren. All rights reserved.
//

import UIKit
/// 用户账号模型
class UserAccount: NSObject,NSCoding {
    /// 登录标记
    class var didLogon : Bool  {
        return sharedAccount != nil
    }
    //    用于调用access_token，接口获取授权后的access token。string
    var access_token:String?
    //    当前授权用户的UID。
    var uid:String?
    //    access_token的生命周期，单位是秒数。
    var expires_in:NSTimeInterval = 0{
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //    过期日期
    var expires_date : NSDate?
    //    友好显示名称
    var name : String?
    //    用户头像地址（大图），180×180像素
    var avatar_large : String?
    //    MARK:- 构造函数－字典转模型
    init(dict:[String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
//        MARK:- 重点 设置全局的用户信息
         UserAccount.userAccount = self
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
//  MARK:- 加载用户
    func loadUserInfo(finished:(error:NSError?)->()){
        WeiboNetWorkingTools.sharedNetWorkingTools.loadUserInfo(uid!) { (result, error) -> () in
            if error != nil{
                finished(error:error)
                return
            }
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            self.saveAccount()
            finished(error: nil)
        }
    }
//    MARK:- 归档和解档的方法
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
//   保存账户
    private func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
//    加载账户
    private static var userAccount:UserAccount?
    class var sharedAccount : UserAccount?{
        if userAccount == nil{
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        }
        //        userAccount!.expires_date = NSDate(timeIntervalSinceNow: -100)
        if let date = userAccount?.expires_date where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{
            userAccount = nil
        }
        return userAccount
    }
//   MARK: - NSCoding
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
    }
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as?String
        uid = aDecoder.decodeObjectForKey("uid") as?String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_date = aDecoder.decodeObjectForKey("expires_date") as?NSDate
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as?String
        name = aDecoder.decodeObjectForKey("name") as?String
    }
    /// 对象描述信息
    override var description: String {
        let properties = ["access_token","expires_in","uid","expires_date","name","avatar_large"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
}
